/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package create_view_modify;

import cse308.entities.Minute;
import cse308.GUIUtilityClass;
import cse308.entities.Degreeprogram;
import cse308.entities.Users;
import cse308.helper_classes.GeneralTest;
import cse308.helper_classes.MinuteClass;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.Part;
import org.omnifaces.util.Faces;

/**
 *
 * @author Aaron
 */
@ManagedBean(name = "minuteBean")
@SessionScoped
public class MinuteBean implements Serializable {

    @ManagedProperty(value = "#{gUIUtilityClass}")
    private GUIUtilityClass utilities;
    private String title;
    private List<MinuteClass> minuteClasses = (List<MinuteClass>) new ArrayList();
    private final static Logger LOG = Logger.getLogger(GUIUtilityClass.class.getName());
    private String identifier;
    private String date;
    private String group;
    private Part minutes;

    public MinuteBean() {
    }

    public String viewMinute() {
        minuteClasses = new ArrayList();
        title = "Minute";
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query minute = em.createNamedQuery("Minute.findAll");
        List<Minute> results = (List<Minute>) minute.getResultList();
        int j = 0;
        for (Minute i : results) {
            List<String> path = new ArrayList();
            path.add(Degreeprogram.class.getSimpleName());
            path.add(Users.class.getSimpleName());
            if(GUIUtilityClass.isUserRole(path, 0, i)){
            MinuteClass currentMinuteClass = new MinuteClass(i);
            minuteClasses.add(currentMinuteClass);
            j++;
            }
        }
        LOG.info("User can see minute info and download files");
        return "minutePage";
    }

    public String modifyMinute() {
        try {
            minuteClasses=(List)utilities.generalizeModify(Minute.class.getCanonicalName(),
                    MinuteClass.class.getCanonicalName(),
                    new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), 
                    new ArrayList<String>());
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            Logger.getLogger(MinuteBean.class.getName()).log(Level.SEVERE, null, ex);
        }
      
        return "ModifyMinute";
    }

    public String saveMinute() {
        ArrayList<GeneralTest> gt = new ArrayList();
        for(int i=0; i<this.minuteClasses.size(); i++){
            gt.add(this.minuteClasses.get(i));
        }
        try {
            boolean success=utilities.generalizedSave(Minute.class.getCanonicalName(), gt, new ArrayList());
             if (!success) {
                FacesMessage message = new FacesMessage();
                message.setDetail(GUIUtilityClass.duplicateWarning);
                FacesContext.getCurrentInstance().addMessage("form", message);
                return "";
            }
            /* EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
            EntityManager em = emf.createEntityManager();
            Query minuteData = em.createNamedQuery("Minute.findAll");
            List<Minute> results = (List<Minute>) minuteData.getResultList();
            for (int i = 0; i < minuteClasses.size(); i++) {
                MinuteClass m1 = minuteClasses.get(i);
                Minute m2 = results.get(i);
                em.getTransaction().begin();
                m2.setDate(m1.getDate());
                m2.setGroup(m1.getGroup());
                em.persist(m2);
                em.getTransaction().commit();
            }
            LOG.info("Commits entities to DB");*/
        } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | ClassNotFoundException | InstantiationException ex) {
            Logger.getLogger(MinuteBean.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "WelcomePage";


    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    
    public List<MinuteClass> getMinuteClasses() {
        return minuteClasses;
    }

    public void setMinuteClasses(List<MinuteClass> minuteClasses) {
        this.minuteClasses = minuteClasses;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public Part getMinutes() {
        return minutes;
    }

    public void setMinutes(Part minutes) {
        this.minutes = minutes;
    }

    public String createMinutes() {
        return "CreateMinute";
    }

    public String createMinute() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        LOG.info("Created new Minute entity");
        Minute minute = new Minute();
        minute.setDate(this.date);
        minute.setGrp(this.group);
        minute.setMinutes(GUIUtilityClass.convertToBytesByPart(this.minutes));
        minute.setIdentifier(this.identifier);
        if (utilities.checkPK(minute)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.createWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        em.persist(minute);
        em.getTransaction().commit();
        LOG.info("Commit entities to DB");

        return "welcome";
    }

   

    public void getMinutes(ActionEvent ae) {
        try {
            Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getAttributes().get("rowIndex");
            File sendTo = this.minuteClasses.get(rowIndex).getMinute();
            if(sendTo==null){
                return;
            }
            Faces.sendFile(sendTo, true);
        } catch (IOException ex) {
            Logger.getLogger(GUIUtilityClass.class.getName()).log(Level.SEVERE, null, ex);
        }
        LOG.info("Downloads selected Minutes");
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public GUIUtilityClass getUtilities() {
        return utilities;
    }

    public void setUtilities(GUIUtilityClass utilities) {
        this.utilities = utilities;
    }
    
}